-- UISkyCityShipSkill
-- Create by cheny3
-- 秘宝主界面

-- UISkyCityShipSkill继承自Layer
UISkyCityShipSkill = class("UISkyCityShipSkill", function()
    return cc.Layer:create();
end);

function UISkyCityShipSkill.create()
    return UISkyCityShipSkill.new();
end

local PAGE_COLUMN   = 4;                -- 最大列数

local tabSkillType  = {-1, 2, 1, 3, 4}; -- 标签对应的显示类型

-- 内部函数声明
local sortSkills;

-- 构造函数
function UISkyCityShipSkill:ctor()
    -- 初始化
    self:setName("UISkyCityShipSkill");
    -- 复用编组界面
    local node = cc.CSLoader:createNode("layout/sky_city/SkyCityTeam.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.pageIndex = 1;

    -- 容器原本的内高
    self.oriHeight = scrollview:getInnerContainerSize().height

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 调整下标题背景图片资源
    local bgTypeImg1 = findChildByName(self.node, "CT/template/bg_type");
    local bgTypeImg2 = findChildByName(self.node, "CT/template/bg_type2");
    bgTypeImg2:setVisible(true);
    bgTypeImg1:loadTexture(getTitleBgIconPath("airship"));
    bgTypeImg2:loadTexture(getTitleBgIconPath("airship"));

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化格子
    self:initGrids(self.node, tabSkillType[self.pageIndex]);

    -- 重绘
    self:redraw(tabSkillType[self.pageIndex]);

    -- 初始化标签页
    self:initTabs();

    -- 适配
    self:resize();
end

-- 初始化标签页
function UISkyCityShipSkill:initTabs()
    local tabNode = findChildByName(self.node, "CT/tab");
    tabNode:setVisible(true);

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    local tabItem = cc.CSLoader:createNode("layout/tab/tab.csb");
    local widget = replaceNodeWithWidget(tabItem);
    for i = 1, #tabSkillType do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");
        tabImage.camp = tabSkillType[i];

        tabIcon:setVisible(true);
        tabText:setPositionX(tabText:getPositionX() + 1);
        TextStyleM.setTextStyle(tabText, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        tabText:setString(self:getTabText()[i]);
        tabText:setVisible(false);

        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        -- 置灰颜色
        local blendColor = TextStyleM.TEXT_COLOR_BLEND;
        local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

        if i == 1 then
            -- 当前标签页高亮
            tabLight:setVisible(true);
            self.pageIndex = i;
            tabImage:loadTexture(getTabIconPath("red"));

            tabIcon:loadTexture(getSmallHeroIconPath("all"));
        else
            tabLight:setVisible(false);
            tabImage:setColor(blendColor);
            tabText:setColor(blendColor);
            tabImage:loadTexture(getTabIconPath("blue"));

            tabIcon:loadTexture(getCampSmallIconPath(tabSkillType[i]));
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UISkyCityShipSkill:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.2 * (i - 1));
        local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 获取标签文本
function UISkyCityShipSkill:getTabText()
    local tabTextArray  = {
        getLocStr("tab_text_all"),
        CampM.query(tabSkillType[2], "name"),
        CampM.query(tabSkillType[3], "name"),
        CampM.query(tabSkillType[4], "name"),
        CampM.query(tabSkillType[5], "name"),
    };
    return tabTextArray;
end

-- 点击标签页
function UISkyCityShipSkill:registerTabTouchEvent(node)
    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local tabImage = node:getChildByName("tab");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除上一个高亮
            local tabNode = findChildByName(self.node, "CT/tab");
            for _, child in pairs(tabNode.rows) do
                if child.index == self.pageIndex then
                    -- 去除高亮
                    local tabLight = findChildByName(child, "light");
                    local tabImage = findChildByName(child, "tab");
                    local tabText  = findChildByName(child, "text");
                    tabLight:setVisible(false);
                    tabImage:setColor(blendColor);
                    tabText:setColor(blendColor);
                end
            end
            -- 设置当前高亮
            local tabLight = findChildByName(node, "light");
            local tabImage = findChildByName(node, "tab");
            local tabText  = findChildByName(node, "text");
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabText:setColor(normalColor);
            self.pageIndex = node.index;

            -- 初始化格子
            self:initGrids(node, tabImage.camp)
            -- 重绘界面
            self:redraw(tabImage.camp);
        end
    end
    tabImage:addTouchEventListener(onClick);
end

-- 适配
function UISkyCityShipSkill:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化格子
function UISkyCityShipSkill:initGrids(node, camp)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 1;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 15;
    local bottomHGap  = 50;
    local leftWGap = 10;

    local allShipSkills = SkyShipSkillM.getAllShipSkills();

    if camp < 0 then
        self.data = allShipSkills;
    else
        local data = {};

        for _, info in ipairs(allShipSkills) do
            if info["camp"] == camp then
                table.insert(data, info);
            end
        end

        self.data = data;
    end

    -- 总数
    local totalCount = #self.data;
    local totalRowNum = math.ceil(totalCount / PAGE_COLUMN);

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    -- 还原容器原本内高
    self.scrollView:setInnerContainerSize(cc.size(self.scrollView:getInnerContainerSize().width, self.oriHeight));

    local itemNode = cc.CSLoader:createNode("layout/sky_city/AirShipSkillItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, totalRowNum, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerItemTouchEvent);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);

        -- 换个背景框
        local bgImg = findChildByName(child, "bg");
        bgImg:loadTexture(getFrameBgIconPath("airship_skill"));
    end
end

-- 重绘界面
function UISkyCityShipSkill:redraw(camp)
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("sky_treasure"));
    if camp > 0 then
        titleLabel:setString(self:getTabText()[self.pageIndex]);
    end

    -- 技能信息
    local skillInfos = table.deepcopy(self.data);

    -- 提前统计一下上阵冈布奥
    for _, info in pairs(skillInfos) do
        -- 判断是否已拥有
        if not SkyShipSkillM.hasOwn(info["id"]) then
            info["hasOwn"] = 0;
            info["activity"] = 0;
            info["activeAmount"] = 0;
        else
            info["hasOwn"] = 1;

            -- 判断是否已激活
            local needAmount = #info["group"];
            local activeAmount = 0;
            for i, id in pairs(info["group"]) do
                if SkyCombatM.isInArmy(id) then
                    activeAmount = activeAmount + 1;
                end
            end
            info["activeAmount"] = activeAmount;

            if activeAmount >= needAmount then
                info["activity"] = 1;
            else
                info["activity"] = 0;
            end
        end
    end

    -- 排序
    table.sort(skillInfos, sortSkills);

    local totalGridCount = #skillInfos;
    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            local info = skillInfos[i];
            --  初始化格子信息
            self:initGridInfo(grid, info);
        end
    end

    -- 屏蔽翻页按钮
    local btnLast = findChildByName(self.node, "CT/btn_last");
    local btnNext = findChildByName(self.node, "CT/btn_next");
    btnNext:setVisible(false);
    btnNext:setVisible(false);
end

-- 对冈布奥进行排序  按（已激活>有上阵>没上阵>未获得 人数越多的秘宝，越靠前）/ ID排序顺序
function sortSkills(item1, item2)
    if item1["hasOwn"] ~= item2["hasOwn"] then
        return item1["hasOwn"] > item2["hasOwn"];
    elseif item1["activity"] ~= item2["activity"] then
        return item1["activity"] > item2["activity"];
    elseif #item1["group"] ~= #item2["group"] then
        return #item1["group"] > #item2["group"];
    elseif item1["activeAmount"] ~= item2["activeAmount"] then
        return item1["activeAmount"] > item2["activeAmount"];
    else
        return item1.id < item2.id;
    end
end

--  初始化格子信息
function UISkyCityShipSkill:initGridInfo(grid, info)
    local bgImg = grid:getChildByName("bg");
    local icon = grid:getChildByName("icon");
    local textLable = grid:getChildByName("text");

    local iconPath = getAirShipSkillIconPath(tostring(info["icon"]));
    icon:loadTexture(iconPath)
    -- 标记技能ID
    grid.index = info["id"];

    -- 判断秘宝是否激活
    local needAmount = #info["group"];
    local activeAmount = info["activeAmount"];

    if info["hasOwn"] ~= 1 then
        setGrayTransMode(bgImg, true);
        bgImg:setOpacity(130);
        icon:setOpacity(180);

        textLable:setVisible(false);
    else
        setGrayTransMode(bgImg, false);
        bgImg:setOpacity(255);
        icon:setOpacity(255);

        local textStr = string.format(getLocStr("attrib_value_format"), activeAmount, needAmount);

        if info["activity"] ~= 1 then
            -- 没激活
            TextStyleM.setTextStyle(textLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true);
        else
            -- 激活
            TextStyleM.setTextStyle(textLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_ORANGE, true);
        end
        textLable:setString(textStr);
        textLable:setVisible(true);
    end
end

-- 注册格子点击事件
function UISkyCityShipSkill:registerItemTouchEvent(node)
    -- 打开详情界面
    local function showInfo(id)
        require "game/ui/form/sky_city/UIAirShipSkillDesc"
        UIMgr.getCurrentScene():removeFormByName("UIAirShipSkillDesc");
        local uiAirShipSkillDesc = UIAirShipSkillDesc.create(id);
        UIMgr.getCurrentScene():addForm(uiAirShipSkillDesc);
        AudioM.playFx("button_spell");
    end

    -- 注册图标点击事件
    local bgImg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            showInfo(node.index);
        end
    end
    bgImg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UISkyCityShipSkill:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyCityShipSkill");
        elseif eventType == "enter" then

        end
    end);
    -- TODO 注册事件回调
end

-- 注册点击事件
function UISkyCityShipSkill:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityShipSkill");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 说明按钮
    local btnExchange = findChildByName(self.node, "BT/btn_info");
    btnExchange:setVisible(false);

    -- 隐藏无用按钮
    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end


